package com.heriparid.slideshow.util;

import java.io.IOException;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Context;
import android.content.res.XmlResourceParser;

import com.heriparid.slideshow.R;
import com.heriparid.slideshow.model.PhotoHolder;

public class XmlResourceReader {

	private static final String TAG = XmlResourceReader.class.getSimpleName();
	
//	private static final String MODELS = "models";
	private static final String ENTRY = "entry";
//	private static final String ID = "id";
	private static final String IMAGE = "image";
	private static final String SOUND = "sound";
	private static final String DESC_SOUND = "descsound";
	private static final String TITLE = "title";
	
	private final Context mContext;
	private final String PACKAGE_NAME;
	private XmlResourceParser mXrp;
	
	private List<PhotoHolder> mContainers;
	
	public XmlResourceReader(Context context, List<PhotoHolder> containers) {
		mContext = context;
		PACKAGE_NAME = mContext.getPackageName();
		mContainers = containers;
	}
	
	public void parse(){
		mXrp = mContext.getApplicationContext().getResources().getXml(R.xml.animals_map);
		try {			
			doParse();
		} catch (XmlPullParserException e) {			
			e.printStackTrace();
		} catch (IOException e) {			
			e.printStackTrace();
		}		
	}

	private void doParse() throws XmlPullParserException, IOException {
		mXrp.next();
		int eventType = mXrp.getEventType();
		int index = 0;
		
		while (eventType != XmlPullParser.END_DOCUMENT) {
		    if (eventType == XmlPullParser.START_TAG) {
		    	
		    	if(mXrp.getName().equalsIgnoreCase(ENTRY)){
//		    		String id = mXrp.getAttributeValue(null, ID);
			        String image = mXrp.getAttributeValue(null, IMAGE);
			        String sound = mXrp.getAttributeValue(null, SOUND);
			        String descSound = mXrp.getAttributeValue(null, DESC_SOUND);
			        String title = mXrp.getAttributeValue(null, TITLE);
			        
			        int imageResId = getResourceId(image);
			        int soundResId = getResourceId(sound);
			        int descSoundResId = getResourceId(descSound);
			        String titleValue = mContext.getString(getResourceId(title));
			        
			        PhotoHolder container = new PhotoHolder(index++, titleValue, imageResId, soundResId, descSoundResId);			        
			        mContainers.add(container);
		    	}	        	        
		        
		    }
		    eventType = mXrp.next();
		}
	}
	
	private int getResourceId(String res){
		int id = -1;
		
		if(res == null || res.length() == 0){
			return id;
		}
		
		String defType = res.substring(1, res.indexOf("/"));
		String name = res.substring(res.indexOf("/") + 1, res.length());
		
		id = mContext.getResources().getIdentifier(name, defType, PACKAGE_NAME);
		
		return id;
	}
}
